#!/usr/bin/env python3
import sys
import itertools
import os
import time

def print_image(image):
    if isinstance(image[0], list):
        print('\n'.join([''.join(['#' if p else '.' for p in row]) for row in image]))
    else:
        print(''.join(['#' if p else '.' for p in image]))

def get_adjacent(x, y):
    return list(itertools.chain.from_iterable([[(x + j, y + i) for i in range(-1, 2)] for j in range(-1, 2)]))

def pad_image(image):
    width, height = len(image[0]), len(image)
    new = [[False for _ in range(width + 2)] for _ in range(height + 2)]
    for y in range(height + 2):
        for x in range(height + 2):
            if x >= 2 and y >= 2:
                new[y - 1][x - 1] = image[y - 2][x - 2]
    return new

def get_binary_encoding(algorithm, image, x, y):
    pixels = [image[a[0]][a[1]] if a[0] >= 0 and a[0] < len(image[0]) and a[1] >= 0 and a[1] < len(image) else False for a in get_adjacent(y, x) ]
    binary_list = [2**(len(pixels) - 1 - i) if p else 0 for i, p in enumerate(pixels)]
    binary = sum(binary_list)
    return algorithm[binary]

def enhance(image):
    padded = pad_image(image)
    for y in range(len(padded)):
        for x in range(len(padded[y])):
            padded[y][x] = get_binary_encoding(algorithm, image, x - 1, y - 1)
    return padded

# parse input
algorithm = [ True if c == '#' else False for c in input()]
image = []
input()
for line in sys.stdin:
    image.append(list(map(lambda x: True if x == '#' else False, [c for c in line.rstrip('\n')])))

# get rounds
rounds = int(sys.argv[1]) if len(sys.argv) > 1 else 2

# render original image
os.system('cls' if os.name == 'nt' else 'clear')
print('converting')
finally_padded_original = image
for _ in range(rounds):
    finally_padded_original = pad_image(finally_padded_original)
print_image(finally_padded_original)
time.sleep(2)

# compute image enhancements
for i in range(rounds):
    # clear
    os.system('cls' if os.name == 'nt' else 'clear')

    # make actual computation
    image = enhance(image)

    # render image by padding it
    finally_padded_enhanced = image
    for _ in range(rounds - i - 1):
        finally_padded_enhanced = pad_image(finally_padded_enhanced)

    # output
    print(f'to (round {i + 1})')
    print_image(finally_padded_enhanced)
    time.sleep(.25)

print(f'{sum([sum([1 for p in row if p]) for row in image])} pixels are lit after {rounds} rounds')